import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

//模拟实现一个线程池
class MyThreadPool {
    //1.有任务队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);//任务队列可以存放1000个Runnable任务
    private int maxPoolSize = 0;
    private List<Thread> threadList = new ArrayList<>();//用于存放已经创建好的线程
    //2.构造方法，用于初始化
    public MyThreadPool(int morePoolSize,int maxPoolSize) {//n就是要初始化多少个线程
        this.maxPoolSize = maxPoolSize;//记录最大的线程数
        for (int i = 0; i < morePoolSize; i++) {//下面根据核心线程数创造
            Thread t = new Thread(()->{
               while (true) {//线程创建后之后，就不断的去执行任务，否则只执行一次任务就会被销毁了
                   try {
                       Runnable runnable = queue.take();//从任务队列中取出任务
                       runnable.run();//执行run中的任务
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
               }

            });
            t.start();
            threadList.add(t);
        }
    }
    //3.提供submit方法
    void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);

        //当任务数到达一定的数量时，自动增加线程
        if(queue.size() >= 500 && threadList.size() < maxPoolSize) {
            Thread t = new Thread(()->{
                while (true) {//线程创建后之后，就不断的去执行任务，否则只执行一次任务就会被销毁了
                    try {
                        Runnable runnable2 = queue.take();//从任务队列中取出任务
                        runnable.run();//执行run中的任务
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

            });
            t.start();
            threadList.add(t);
        }
    }
}

public class Test2 {

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool threadPool = new MyThreadPool(10,20);//核心线程、最大线程
        for (int i = 0; i < 101; i++) {//循环向线程池中插入任务
            int id = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("我是第"+id+"个任务"+Thread.currentThread().getName());
                }
            });
        }
    }
}
